package jdbc;

import java.sql.*;

/**
 * JDBC API详解:Connection :
 *      void setAutoCommit(boolean autoCommit) throws SQLException; 开启事务,参数为true 为自动提交,false为手动提交
 *      void commit() throws SQLException; 提交事务
 *      void rollback() throws SQLException; 回滚事务
 *
 */
public class ConnectionDemo {
    public static void main(String[] args) throws SQLException {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_database?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true",
                "root", "1234");

        Statement stat = conn.createStatement();

        try {
            // 开启事务
            conn.setAutoCommit(false); // true 为自动提交,false为手动提交
            String sql1 = "update account set money = money - 1000 where id = 1 ";
            int i = stat.executeUpdate(sql1);
            System.out.println(i);

            // 手动制造异常
            stat.execute("wefds");

            String sql2 = "update account set money = money + 1000 where id = 2";
            int i2 = stat.executeUpdate(sql2);
            System.out.println(i2);

            // 提交事务
            conn.commit();

        } catch (Exception e) {
            // 回滚事务
            conn.rollback();
            e.printStackTrace();
        }

        conn.close();
        stat.close();

    }
}
